﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using IGolovkine.Core.Diagnostics;

namespace IGolovkine.ShoutCastRipper.Filters
{
    public class ContentTitleAgeFilter : IContentTitleFilter
    {
        private readonly TimeSpan _maxAge;
        private readonly IContentTitleDateExtractor _dateExtractor;

        public ContentTitleAgeFilter(TimeSpan maxAge, IContentTitleDateExtractor dateExtractor)
        {
            Debug.NotDefault(() => maxAge);
            Debug.NotDefault(() => dateExtractor);

            _maxAge = maxAge;
            _dateExtractor = dateExtractor;
        }

        public string Name
        {
            get { return "Age Filter"; }
        }

        public ContentTitleFilterResult Process(string streamTitle)
        {
            TimeSpan titleAge = this.GetTitleAge(streamTitle);
            if (titleAge > _maxAge)
            {
                return ContentTitleFilterResult.RejectedResult("Content age of {0:0} days exceeds the maximum permissible age of {1:0} days", titleAge.TotalDays, _maxAge.TotalDays);
            }
            else
            {
                return ContentTitleFilterResult.AcceptedResult();
            }
        }

        private TimeSpan GetTitleAge(string recordingName)
        {
            DateTime recordingDate = DateTime.MaxValue;
            if (_dateExtractor.TryGetContentDate(recordingName, out recordingDate))
            {
                if (recordingDate < DateTime.Now)
                {
                    return DateTime.Now - recordingDate;
                }
            }

            return TimeSpan.Zero;
        }
    }
}
